package com.itkjb.leisurely.resource.sys.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itkjb.leisurely.core.base.BaseConstants;
import com.itkjb.leisurely.core.base.BaseDto;
import com.itkjb.leisurely.core.base.BaseResult;
import com.itkjb.leisurely.core.base.controller.BaseController;
import com.itkjb.leisurely.core.model.PageModel;
import com.itkjb.leisurely.core.model.RequestUserInfoModel;
import com.itkjb.leisurely.core.model.SearchModel;
import com.itkjb.leisurely.core.util.QueryUtil;
import com.itkjb.leisurely.core.util.RequestUserInfoUtil;
import com.itkjb.leisurely.resource.sys.model.SysUserRoleModel;
import com.itkjb.leisurely.resource.sys.model.dto.SysRoleUserDTO;
import com.itkjb.leisurely.resource.sys.model.vo.SysUserRoelVO;
import com.itkjb.leisurely.resource.sys.model.vo.SysUserVO;
import com.itkjb.leisurely.resource.sys.service.ISysUserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
 * <p>
 * 用户绑定角色 接口层
 * </p>
 *
 * @author itkjb.com
 * @since 2020-07-17
 */
@RestController
@RequestMapping("/sys/sys-user-role")
@Api(value="用户绑定角色",tags={"用户与角色绑定关系相关接口"})
public class SysUserRoleController extends BaseController<SysUserRoleModel,ISysUserRoleService> {

    /**
     * 获取用户绑定角色列表
     * @param param 查询通用参数
     * @param model 特定条件参数
     * @param request
     * @param response
     * @return
     */
    @GetMapping
    @ApiOperation(value="获取用户绑定角色列表",notes="支持分页参数")
    @PreAuthorize("hasAnyAuthority('SysRole:SysRoleUser','SysRole:SysRoleUser:query','SysRoleUser','SysRoleUser:query') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<IPage<SysUserRoleModel>> page(BaseDto param, SysUserRoleModel model, HttpServletRequest request, HttpServletResponse response){
        BaseResult<IPage<SysUserRoleModel>> res = new BaseResult<>();
        res = super.page(param, model);
        return res;
    }

    /**
     * 获取指定角色已绑定的用户列表
     * @param param
     * @param model
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/getUsersByRoleId")
    @ApiOperation(value="获取指定角色已绑定的用户列表",notes="支持分页参数")
    @PreAuthorize("hasAnyAuthority('SysRole:SysRoleUser','SysRole:SysRoleUser:query','SysRoleUser','SysRoleUser:query') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<IPage<SysUserVO>> getUsersByRoleId(BaseDto param, SysUserRoelVO model, HttpServletRequest request, HttpServletResponse response){
        return getUsersByRoleId(param,model,true);
    }

    /**
     * 获取指定角色未绑定的用户列表
     * @param param
     * @param model
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/getUsersByRoleIdNotBind")
    @ApiOperation(value="获取指定角色已绑定的用户列表",notes="支持分页参数")
    @PreAuthorize("hasAnyAuthority('SysRole:SysRoleUser','SysRole:SysRoleUser:query2','SysRoleUser','SysRoleUser:query2') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<IPage<SysUserVO>> getUsersByRoleIdNotBind(BaseDto param, SysUserRoelVO model, HttpServletRequest request, HttpServletResponse response){
        return getUsersByRoleId(param,model,false);
    }

    /**
     * 根据角色id   获取（绑定/未绑定）的用户列表
     * @param param
     * @param model
     * @param isbind
     * @return
     */
    private BaseResult<IPage<SysUserVO>> getUsersByRoleId(BaseDto param, SysUserRoelVO model,boolean isbind){
        BaseResult<IPage<SysUserVO>> res = new BaseResult<>();
        if(model ==null || StringUtils.isBlank(model.getRoleId())){
            return res.setMsg("请先选择一个角色");
        }
        PageModel<?> pageModel = new PageModel<>();
        BeanUtils.copyProperties(param, pageModel);
        if(isbind){
            IPage<SysUserVO> data = this.baseService.getUsersByRoleId(pageModel, model);
            res.toSuccess().setData(data);
        }else{
            IPage<SysUserVO> data = this.baseService.getUsersByRoleIdNotBind(pageModel, model);
            res.toSuccess().setData(data);
        }
        return res;
    }

    /**
     * 根据指定的用户id，获取用户已经绑定的角色
     * @param userId
     * @return
     */
    @GetMapping("/getRolesByUserId/{userId}")
    @ApiOperation(value="获取用户绑定角色列表")
    @PreAuthorize("hasAnyAuthority('SysRole:SysRoleUser:info','SysUser:SysRoleUser:info') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<List<SysUserRoleModel>> getRolesByUserId(@PathVariable("userId") String userId){
        BaseResult<List<SysUserRoleModel>> res = new BaseResult<>();
        if(StringUtils.isBlank(userId)){
            res.setMsg("请选择用户");
        }else{
            SysUserRoleModel model = new SysUserRoleModel();
            model.setUserId(userId);
            List<SysUserRoleModel> roles = this.baseService.getRolesByUserId(model);
            res.setData(roles);
            res.toSuccess();
        }
        return res;
    }


    /**
     * 根据指定的用户id和指定部门id，获取用户在某组织下的角色
     * @param param
     * @return
     */
    @GetMapping("/getRolesByUserAndDep")
    @ApiOperation(value="获取某用户在某组织下的角色",notes = "参数为用户id，和组织id")
    @PreAuthorize("hasAnyAuthority('SysRole:SysRoleUser','SysRole:SysRoleUser:info','SysRoleUser','SysRoleUser:info','SysDepUser:info') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<List<SysUserRoleModel>> getRolesByUserAndDep(SysUserRoleModel param){
        BaseResult<List<SysUserRoleModel>> res = new BaseResult<>();
        if(StringUtils.isBlank(param.getUserId())){
            res.setMsg("请选择用户");
        }else{
            List<SysUserRoleModel> roles = this.baseService.getRolesByUserId(param);
            res.setData(roles);
            res.toSuccess();
        }
        return res;
    }

    /**
     * 获取用户绑定角色列表
     * @param param 查询通用参数，分页参数不可用
     * @param model 特定条件参数
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/list")
    @ApiOperation(value="获取用户绑定角色列表",notes="不支持分页")
    @PreAuthorize("hasAnyAuthority('SysRole:SysRoleUser','SysRole:SysRoleUser:query','SysRoleUser','SysRoleUser:query') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<List<SysUserRoleModel>> list(BaseDto param,SysUserRoleModel model, HttpServletRequest request, HttpServletResponse response){
        BaseResult<List<SysUserRoleModel>> res = new BaseResult<>();
        // 代码生成器生成的下面执行结果默认关闭，防止获取非法数据和数据量过大，若需要手动打开，并做好防护措施
        // return super.list(param, model);
        res.toSuccess().setMsg("注意：无结果返回，默认关闭list查询");
        return res;
    }
    /**
     * 新增角色绑定用户
     * @param param
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/addUserIdsByRoleId")
    @ApiOperation(value="新增角色绑定用户",notes="")
    @PreAuthorize("hasAnyAuthority('SysRole:SysRoleUser:add','SysRoleUser:add') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<SysUserRoleModel> addUserIdsByRoleId(@Valid @RequestBody SysUserRoelVO param, HttpServletRequest request, HttpServletResponse response){
        BaseResult<SysUserRoleModel> res = new BaseResult<>();
        if(StringUtils.isBlank(param.getRoleId())){
            return  res.setMsg("请指定角色再进行绑定用户操作");
        }else if(param.getUserIds() ==null || param.getUserIds().size()<=0){
            return res.setMsg("请指定要绑定的用户");
        }
        List<SysUserRoleModel> userRoleModels = new ArrayList<>();
        param.getUserIds().forEach(userid ->{
            SysUserRoleModel userRoleModel = new SysUserRoleModel();
            userRoleModel.setRoleId(param.getRoleId());
            userRoleModel.setUserId(userid);
            // 设置创建人 和更新人
            userRoleModels.add(userRoleModel);
        });
        boolean b = this.baseService.saveBatch(userRoleModels);
        if(b){
            res.toSuccess();
        }
        return res;
    }
    /**
     * 移除角色绑定的用户
     * @param param
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/removeUserIdsByRoleId")
    @ApiOperation(value="移除角色绑定的用户",notes="")
    @PreAuthorize("hasAnyAuthority('SysRole:SysRoleUser:edit','SysRoleUser:edit') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<SysUserRoleModel> removeUserIdsByRoleId(@Valid @RequestBody SysUserRoelVO param, HttpServletRequest request, HttpServletResponse response){
        BaseResult<SysUserRoleModel> res = new BaseResult<>();
        if(StringUtils.isBlank(param.getRoleId())){
            return  res.setMsg("请指定角色再进行解绑用户操作");
        }else if(param.getUserIds() ==null || param.getUserIds().size()<=0){
            return res.setMsg("请指定要解绑的用户");
        }
        if(this.baseService.removeUserIdsByRoleId(param)){
            res.toSuccess();
        }
        return res;
    }


    /**
     * 新增用户绑定角色
     * @param param
     * @param request
     * @param response
     * @return
     */
    @PostMapping
    @ApiOperation(value="新增用户绑定角色",notes="")
    @PreAuthorize("hasAnyAuthority('SysRole:SysRoleUser:add','SysRoleUser:add') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<SysUserRoleModel> add(@Valid @RequestBody SysUserRoleModel param, HttpServletRequest request, HttpServletResponse response){
        BaseResult<SysUserRoleModel> res = new BaseResult<>();
        res = super.add(param);
        return res;
    }

    /**
     * 获取用户绑定角色详情
     * @param id
     * @param response
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value="获取用户绑定角色详情",notes="")
    @ApiParam(name = "id",type = "Serializable",required = true)
    @PreAuthorize("hasAnyAuthority('SysRole:SysRoleUser:info','SysRoleUser:info') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<SysUserRoleModel> info(@PathVariable("id") Serializable id, HttpServletRequest request, HttpServletResponse response){
        BaseResult<SysUserRoleModel> res = new BaseResult<>();
        res = super.info(id);
        return res;
    }

    /**
     * 修改用户绑定角色
     * @param param
     * @param request
     * @param response
     * @return
     */
    @PutMapping
    @ApiOperation(value="修改用户绑定角色",notes="")
    @PreAuthorize("hasAnyAuthority('SysRole:SysRoleUser:edit','SysRoleUser:edit') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<SysUserRoleModel> edit(@RequestBody SysUserRoleModel param,HttpServletRequest request, HttpServletResponse response){
        BaseResult<SysUserRoleModel> res = new BaseResult<>();
        res =  super.edit(param);
        return res;
    }

    /**
     * 删除用户绑定角色
     * @param ids
     * @param request
     * @param response
     * @return
     */
    @DeleteMapping
    @ApiOperation(value="删除用户绑定角色",notes="注意参数是数字，就算单个，也要以数字的形式传递")
    @PreAuthorize("hasAnyAuthority('SysRole:SysRoleUser:del','SysRoleUser:del') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<SysUserRoleModel> delete(@RequestBody String[] ids, HttpServletRequest request, HttpServletResponse response){
        BaseResult<SysUserRoleModel> res = new BaseResult<>();
        res = super.delete(ids);
        return res;
    }
    // 未加权限认证

    /**
     * 根据角色编码获取用户
     * @param param
     * @param model
     * @return
     */
    @GetMapping("/getRoleUserByCode")
    @ApiOperation(value = "根据角色编码获取用户", notes = "只要用户登录了，未加权限")
    public BaseResult<IPage<SysUserVO>> getRoleUserByCode(BaseDto  param, @Valid SysRoleUserDTO model){
        BaseResult<IPage<SysUserVO>> res = new BaseResult<>();
        if(param == null) {
            res.toSuccess().setMsg("分页参数缺失");
            return res;
        }else {
            if (param.getSize() < 0L) {
                param.setSize(100L);
            }
            SearchModel<SysRoleUserDTO> searchModel = QueryUtil.build(param, model);
            IPage<SysUserVO> data = this.baseService.getUsersByRoleCode(searchModel);
            res = res.toSuccess();
            res.setData(data);
            return res;
        }
    }
    //** **** 用户自生接口 ***** 不需要权限

    /**
     * 获取用户自身已经绑定的角色，（不需要权限）
     * @return
     */
    @GetMapping("/getRolesBySelf")
    @ApiOperation(value="获取用户自己已经绑定的角色",notes = "只要用户登录了，不需要权限",tags = "用户自身相关接口")
    public BaseResult<List<SysUserRoleModel>> getRolesBySelf(){
        BaseResult<List<SysUserRoleModel>> res = new BaseResult<>();
        RequestUserInfoModel requestUserInfoModel = RequestUserInfoUtil.getRequestUserInfoModel();
        SysUserRoleModel model =new SysUserRoleModel();
        model.setUserId(requestUserInfoModel.getUserId());
        List<SysUserRoleModel> roles = this.baseService.getRolesByUserId(model);
        res.setData(roles);
        res.toSuccess();
        return res;
    }

}

